package com.example.earthonline;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

public class TimerFrament extends Fragment {

    private TextView timerTextView;
    private long startTime;
    private long elapsedTime;
    private final long MAX_TIME = 86400 * 1000; // 24 hours in milliseconds

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        timerTextView = view.findViewById(R.id.timerTextView);

        // Start the timer
        startTime = SystemClock.elapsedRealtime();
        view.post(this::updateTimer); // Use the view's post method

        return view;
    }

    private void updateTimer() {
        elapsedTime = SystemClock.elapsedRealtime() - startTime;
        String timeString = formatTime(elapsedTime);
        timerTextView.setText(timeString);

        if (elapsedTime < MAX_TIME) {
            // Update the timer every 1000 milliseconds (1 second)
            getView().postDelayed(this::updateTimer, 1000);
        } else {
            timerTextView.setText("24:00:00");
        }
    }
    // 格式化时间显示
    private String formatTime(long milliseconds) {
        int hours = (int) (milliseconds / 3600000);
        int minutes = (int) ((milliseconds % 3600000) / 60000);
        int seconds = (int) ((milliseconds % 60000) / 1000);
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    @Override
    public void onPause() {
        super.onPause();
        getView().removeCallbacks(this::updateTimer);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTime = SystemClock.elapsedRealtime() - elapsedTime;
        updateTimer();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getView().removeCallbacks(this::updateTimer);
    }
}